#include "arpa/inet.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "sys/socket.h"
#include "sys/types.h"
#include "unistd.h"

#define oops(m) \
  {             \
    perror(m);  \
    exit(1);    \
  }

int main(int ac, char *av[]) {
  // step 1: get a socket
  int sock_id = socket(PF_INET, SOCK_STREAM, 0);
  if (sock_id == -1) {
    oops("socket");
  }

  // step 2: connect to server
  struct sockaddr_in serv_addr;
  memset((void *)&serv_addr, 0, sizeof(serv_addr));
  const char *ip = av[1];  // server ip
  serv_addr.sin_addr.s_addr = inet_addr(ip);
  serv_addr.sin_port = htons(atoi(av[2]));  // port number
  serv_addr.sin_family = AF_INET;

  if (connect(sock_id, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) != 0) {
    oops("connect");
  }

  // step 3: read and write
  char buf[BUFSIZ];
  int n_read = read(sock_id, buf, BUFSIZ);
  if (n_read == -1) {
    oops("read");
  }

  if (write(1, buf, n_read) == -1) {
    oops("write");
  }

  close(sock_id);
  return 0;
}